package blog

import (
	"GinBlog/global"
	"GinBlog/models"
	"GinBlog/models/request"
	"GinBlog/models/response"
	"GinBlog/utils"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type UserApi struct{}

func (u *UserApi) HelloWorld(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "hello world",
	})
}

// @Tags      登录
// @Summary   登录
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.Login true "登录信息"
// @Success   200   {object}  response.Response{msg=string} "登录成功"
// @Router    /blog/user/login [post]
func (ua *UserApi) Login(c *gin.Context) {
	var loginRequest request.Login
	err := c.ShouldBindJSON(&loginRequest)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
	}

	u := &models.User{
		Username: loginRequest.Username,
	}
	global.DB.First(&u)
	//查询用户
	if u.ID == 0 {
		global.Logger.Info("用户不存在",
			zap.String("Username", loginRequest.Username),
			zap.String("Password", loginRequest.Password),
		)
		response.FailWithMessage("用户不存在", c)
	}
	ua.TokenNext(c, *u)

}

// @Tags      注册
// @Summary   注册用户
// @accept    application/json
// @Produce   application/json
// @Param     data  body      request.Register true "注册信息"
// @Success   200   {object}  response.Response{msg=string} "注册成功"
// @Router    /blog/user/register [post]
func (ua *UserApi) Register(c *gin.Context) {
	var registerRequest request.Register
	err := c.ShouldBindJSON(&registerRequest)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
	}

	// 假设生日格式为 "2006-01-02"
	birthday, err := time.Parse("2006-01-02", registerRequest.Birthday)
	if err != nil {
		global.Logger.Info("日期格式错误",
			zap.String("Username", registerRequest.Birthday),
		)
		response.FailWithMessage("日期格式错误", c)
		return
	}
	u := &models.User{
		Username: registerRequest.Username,
		Email:    &registerRequest.Email,
		Phone:    &registerRequest.Phone,
		Password: registerRequest.Password,
		Birthday: &birthday,
	}
	err = userService.Create(u)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	ua.TokenNext(c, *u)
}

/**
 * 下发token
 */
func (ua *UserApi) TokenNext(c *gin.Context, user models.User) {

	token, claims, err := utils.LoginToken(&user)
	if err != nil {
		global.Logger.Error("获取token失败",
			zap.String("UserId", string(user.ID)),
			zap.String("Username", string(user.Username)),
		)
		response.FailWithMessage("获取token失败", c)
	}
	response.OkWithData(response.Login{
		User:      user,
		Token:     token,
		ExpiredAt: claims.ExpiresAt.Unix(),
	}, c)
}
